/*!
 * @file        main.c
 *
 * @brief       Main program body
 *
 * @version     V1.0.0
 *
 * @date        2022-05-25
 *
 * @attention
 *
 *  Copyright (C) 2021-2022 Geehy Semiconductor
 *
 *  You may not use this file except in compliance with the
 *  GEEHY COPYRIGHT NOTICE (GEEHY SOFTWARE PACKAGE LICENSE).
 *
 *  The program is only for reference, which is distributed in the hope
 *  that it will be usefull and instructional for customers to develop
 *  their software. Unless required by applicable law or agreed to in
 *  writing, the program is distributed on an "AS IS" BASIS, WITHOUT
 *  ANY WARRANTY OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the GEEHY SOFTWARE PACKAGE LICENSE for the governing permissions
 *  and limitations under the License.
 */

#include "main.h"

/** printf message */
#define MESSAGE0    "****************************************"
#define MESSAGE1    "* APM32F40x DMC SDRAM Example "
#define MESSAGE2    "* AHB Clock       :"
#define MESSAGE3    "* SDRAM Clock Psc :"
#define MESSAGE4    "* SDRAM Clock     :"

/** printf function configs to USART2 */
#define DEBUG_USART  USART2

/** SDRAM GPIO */
#define  RCM_SDRAM_GPIO_PERIPH (RCM_AHB1_PERIPH_GPIOA | \
                                RCM_AHB1_PERIPH_GPIOD | \
                                RCM_AHB1_PERIPH_GPIOF | \
                                RCM_AHB1_PERIPH_GPIOG | \
                                RCM_AHB1_PERIPH_GPIOH | \
                                RCM_AHB1_PERIPH_GPIOI )

#define RCM_AHB3_PERIPH_EMMC    (0x00000001)

/** SDRAM Address */
#define SDRAM_START_ADDR ((uint32_t)0x60000000)
#define SDRAM_END_ADDR   ((uint32_t)0x60200000)

volatile uint32_t tick = 0;

/** function */
void SDRAM_Init(void);
void SDRAM_GPIOConfig(void);

uint32_t DMC_SDRAM_WriteRead_8Bit(void);
uint32_t DMC_SDRAM_WriteRead_16Bit(void);
uint32_t DMC_SDRAM_WriteRead_32Bit(void);

/*!
 * @brief       Main program
 *
 * @param       None
 *
 * @retval      None
 */
int main(void)
{
    USART_Config_T usartConfig;
    uint32_t sdramClock,sdramDiv;

    /** Configures COM port. */
    usartConfig.baudRate = 115200;
    usartConfig.hardwareFlow = USART_HARDWARE_FLOW_NONE;
    usartConfig.mode = USART_MODE_TX;
    usartConfig.parity = USART_PARITY_NONE;
    usartConfig.stopBits = USART_STOP_BIT_1;
    usartConfig.wordLength = USART_WORD_LEN_8B;
    APM_EVAL_COMInit(COM2, &usartConfig);

    /** SDRAM Clock: HCLK / SDRAMPSC */
    RCM_ConfigSDRAM(RCM_SDRAM_DIV_4);
    sdramDiv = ((1 << RCM->CFG_B.SDRAMPSC) > 2) ? 4 : (1 << RCM->CFG_B.SDRAMPSC);
    sdramClock = (RCM_ReadHCLKFreq() / sdramDiv) / 1000000;

    /** printf message */
    printf("\r\n");
    printf("%s \r\n", MESSAGE0);
    printf("%s \r\n", MESSAGE1);
    printf("%s %d MHz\r\n", MESSAGE2, RCM_ReadHCLKFreq() / 1000000);
    printf("%s %d div\r\n", MESSAGE3, sdramDiv);
    printf("%s %d MHz\r\n", MESSAGE4, sdramClock);

    SDRAM_GPIOConfig();
    SDRAM_Init();
 
    /** SDRAM bit test */
    DMC_SDRAM_8BitTest();
    DMC_SDRAM_16BitTest();
    DMC_SDRAM_32BitTest();
    
    printf("%s \r\n", MESSAGE0);
    while (1)
    {
    }
}

/*!
 * @brief       SDRAM GPIO Config
 *
 * @param       None
 *
 * @retval      None
 *
 */
void SDRAM_GPIOConfig(void)
{
    GPIO_Config_T gpioConfig;

    RCM_EnableAHB1PeriphClock(RCM_SDRAM_GPIO_PERIPH);

    gpioConfig.speed = GPIO_SPEED_50MHz;
    gpioConfig.mode = GPIO_MODE_AF;
    gpioConfig.otype = GPIO_OTYPE_PP;
    gpioConfig.pupd = GPIO_PUPD_NOPULL;

    gpioConfig.pin = GPIO_PIN_10 | GPIO_PIN_12 |
                     GPIO_PIN_13 | GPIO_PIN_14 |
                     GPIO_PIN_15;
    GPIO_Config(GPIOD, &gpioConfig);
    
    GPIO_ConfigPinAF(GPIOD, GPIO_PIN_SOURCE_10, GPIO_AF_EMMC);
    GPIO_ConfigPinAF(GPIOD, GPIO_PIN_SOURCE_12, GPIO_AF_EMMC);
    GPIO_ConfigPinAF(GPIOD, GPIO_PIN_SOURCE_13, GPIO_AF_EMMC);
    GPIO_ConfigPinAF(GPIOD, GPIO_PIN_SOURCE_14, GPIO_AF_EMMC);
    GPIO_ConfigPinAF(GPIOD, GPIO_PIN_SOURCE_15, GPIO_AF_EMMC);

    gpioConfig.pin = GPIO_PIN_0 | GPIO_PIN_1 |
                     GPIO_PIN_2 | GPIO_PIN_3 |
                     GPIO_PIN_4 | GPIO_PIN_6 |
                     GPIO_PIN_7 | GPIO_PIN_8 |
                     GPIO_PIN_9 | GPIO_PIN_10 |
                     GPIO_PIN_11;
    GPIO_Config(GPIOF, &gpioConfig);
    
    GPIO_ConfigPinAF(GPIOF, GPIO_PIN_SOURCE_0, GPIO_AF_EMMC);
    GPIO_ConfigPinAF(GPIOF, GPIO_PIN_SOURCE_1, GPIO_AF_EMMC);
    GPIO_ConfigPinAF(GPIOF, GPIO_PIN_SOURCE_2, GPIO_AF_EMMC);
    GPIO_ConfigPinAF(GPIOF, GPIO_PIN_SOURCE_3, GPIO_AF_EMMC);
    GPIO_ConfigPinAF(GPIOF, GPIO_PIN_SOURCE_4, GPIO_AF_EMMC);
    GPIO_ConfigPinAF(GPIOF, GPIO_PIN_SOURCE_6, GPIO_AF_EMMC);
    GPIO_ConfigPinAF(GPIOF, GPIO_PIN_SOURCE_7, GPIO_AF_EMMC);
    GPIO_ConfigPinAF(GPIOF, GPIO_PIN_SOURCE_8, GPIO_AF_EMMC);
    GPIO_ConfigPinAF(GPIOF, GPIO_PIN_SOURCE_9, GPIO_AF_EMMC);
    GPIO_ConfigPinAF(GPIOF, GPIO_PIN_SOURCE_10, GPIO_AF_EMMC);
    GPIO_ConfigPinAF(GPIOF, GPIO_PIN_SOURCE_11, GPIO_AF_EMMC);

    gpioConfig.pin = GPIO_PIN_1 | GPIO_PIN_2 |
                     GPIO_PIN_3 | GPIO_PIN_4 |
                     GPIO_PIN_5 | GPIO_PIN_6 |
                     GPIO_PIN_8 | GPIO_PIN_15;
    GPIO_Config(GPIOG, &gpioConfig);
    
    GPIO_ConfigPinAF(GPIOG, GPIO_PIN_SOURCE_1, GPIO_AF_EMMC);
    GPIO_ConfigPinAF(GPIOG, GPIO_PIN_SOURCE_2, GPIO_AF_EMMC);
    GPIO_ConfigPinAF(GPIOG, GPIO_PIN_SOURCE_3, GPIO_AF_EMMC);
    GPIO_ConfigPinAF(GPIOG, GPIO_PIN_SOURCE_4, GPIO_AF_EMMC);
    GPIO_ConfigPinAF(GPIOG, GPIO_PIN_SOURCE_5, GPIO_AF_EMMC);
    GPIO_ConfigPinAF(GPIOG, GPIO_PIN_SOURCE_6, GPIO_AF_EMMC);
    GPIO_ConfigPinAF(GPIOG, GPIO_PIN_SOURCE_8, GPIO_AF_EMMC);
    GPIO_ConfigPinAF(GPIOG, GPIO_PIN_SOURCE_15, GPIO_AF_EMMC);

    gpioConfig.pin = GPIO_PIN_3 | GPIO_PIN_5 |
                     GPIO_PIN_8 | GPIO_PIN_10 |
                     GPIO_PIN_13 | GPIO_PIN_15;
    GPIO_Config(GPIOH, &gpioConfig);
    
    GPIO_ConfigPinAF(GPIOH, GPIO_PIN_SOURCE_3, GPIO_AF_EMMC);
    GPIO_ConfigPinAF(GPIOH, GPIO_PIN_SOURCE_5, GPIO_AF_EMMC);
    GPIO_ConfigPinAF(GPIOH, GPIO_PIN_SOURCE_8, GPIO_AF_EMMC);
    GPIO_ConfigPinAF(GPIOH, GPIO_PIN_SOURCE_10, GPIO_AF_EMMC);
    GPIO_ConfigPinAF(GPIOH, GPIO_PIN_SOURCE_13, GPIO_AF_EMMC);
    GPIO_ConfigPinAF(GPIOH, GPIO_PIN_SOURCE_15, GPIO_AF_EMMC);

    gpioConfig.pin = GPIO_PIN_3 | GPIO_PIN_7 |
                     GPIO_PIN_8 | GPIO_PIN_9 |
                     GPIO_PIN_10 | GPIO_PIN_11;
    GPIO_Config(GPIOI, &gpioConfig);
    
    GPIO_ConfigPinAF(GPIOI, GPIO_PIN_SOURCE_3, GPIO_AF_EMMC);
    GPIO_ConfigPinAF(GPIOI, GPIO_PIN_SOURCE_7, GPIO_AF_EMMC);
    GPIO_ConfigPinAF(GPIOI, GPIO_PIN_SOURCE_8, GPIO_AF_EMMC);
    GPIO_ConfigPinAF(GPIOI, GPIO_PIN_SOURCE_9, GPIO_AF_EMMC);
    GPIO_ConfigPinAF(GPIOI, GPIO_PIN_SOURCE_10, GPIO_AF_EMMC);
    GPIO_ConfigPinAF(GPIOI, GPIO_PIN_SOURCE_11, GPIO_AF_EMMC);
}

void SDRAM_Init(void)
{
    uint32_t sdramCapacity;
    DMC_Config_T dmcConfig;
    DMC_TimingConfig_T timingConfig;

    RCM_EnableAHB3PeriphClock(RCM_AHB3_PERIPH_EMMC);

    timingConfig.latencyCAS = DMC_CAS_LATENCY_3;        //!< Configure CAS latency period
    timingConfig.tARP       = DMC_AUTO_REFRESH_10;      //!< Configure auto refresh period
    timingConfig.tRAS       = DMC_RAS_MINIMUM_2;        //!< Configure line activation and precharging minimum time
    timingConfig.tCMD       = DMC_ATA_CMD_1;            //!< Configure active to active period
    timingConfig.tRCD       = DMC_DELAY_TIME_1;         //!< Configure RAS To CAS delay Time
    timingConfig.tRP        = DMC_PRECHARGE_1;          //!< Configure precharge period
    timingConfig.tWR        = DMC_NEXT_PRECHARGE_2;     //!< Configure time between the Last Data and The Next Precharge for write
    timingConfig.tXSR       = 3;                        //!< Configure XSR0
    timingConfig.tRFP       = 0x2F9;                    //!< Configure refresh Cycle

    dmcConfig.bankWidth     = DMC_BANK_WIDTH_1;         //!< Configure bank address width
    dmcConfig.clkPhase      = DMC_CLK_PHASE_REVERSE;    //!< Configure clock phase
    dmcConfig.rowWidth      = DMC_ROW_WIDTH_11;         //!< Configure row address width
    dmcConfig.colWidth      = DMC_COL_WIDTH_8;          //!< Configure column address width
    dmcConfig.timing        = timingConfig;

    DMC_Config(&dmcConfig);
    DMC_ConfigOpenBank(DMC_BANK_NUMBER_2);
    DMC_EnableAccelerateModule();

    DMC_Enable();

    /** sdramCapacity = row * col * 16bit * bank (16bit == 2Bytes) */
    sdramCapacity = (1 << (dmcConfig.rowWidth + 1)) * (1 << (dmcConfig.colWidth + 1)) * 2 * (1 << (dmcConfig.bankWidth + 1));
    
    printf("* Row Address Width    :%d bit\r\n", dmcConfig.rowWidth + 1);
    printf("* Column Address Width :%d bit\r\n", dmcConfig.colWidth + 1);
    printf("* Bank Address Width   :%d bit band addr\r\n", dmcConfig.bankWidth + 1);
    printf("* capacity             :%d MByte\r\n", sdramCapacity / 1024 / 1024);
}

/*!
 * @brief       SDRAM 8bit Test
 *
 * @param       None
 *
 * @retval      None
 *
 */
void DMC_SDRAM_8BitTest(void)
{
    uint32_t WriteReadStatus=0;

    printf("%s \r\n", MESSAGE0);
    printf("    Test 8 bits read and write operation on the 2MB bytes space of external SDRAM\r\n");

    WriteReadStatus = DMC_SDRAM_WriteRead_8Bit();
    
    if (WriteReadStatus != 0)
    {
        printf("    Check failed, error address:0x%X\r\n", WriteReadStatus);
    }
    else
    {
        printf("    Check passed\r\n");
    }
}


/*!
 * @brief       SDRAM 16bit Test
 *
 * @param       None
 *
 * @retval      None
 *
 */
void DMC_SDRAM_16BitTest(void)
{
    uint32_t WriteReadStatus=0;

    printf("%s \r\n", MESSAGE0);
    printf("    Test 16 bits read and write operation on the 2MB bytes space of external SDRAM\r\n");

    WriteReadStatus = DMC_SDRAM_WriteRead_16Bit();
    
    if (WriteReadStatus != 0)
    {
        printf("    Check failed, error address:0x%X\r\n", WriteReadStatus);
    }
    else
    {
        printf("    Check passed\r\n");
    }
}

/*!
 * @brief       SDRAM 32bit Test
 *
 * @param       None
 *
 * @retval      None
 *
 */
void DMC_SDRAM_32BitTest(void)
{
    uint32_t WriteReadStatus=0;

    printf("%s \r\n", MESSAGE0);
    printf("    Test 32 bits read and write operation on the 2MB bytes space of external SDRAM\r\n");

    WriteReadStatus = DMC_SDRAM_WriteRead_32Bit();
    
    if (WriteReadStatus != 0)
    {
        printf("    Check failed, error address:0x%X\r\n", WriteReadStatus);
    }
    else
    {
        printf("    Check passed\r\n");
    }
}

/*!
 * @brief       SDRAM 8bit Write Read
 *
 * @param       None
 *
 * @retval      None
 */
uint32_t DMC_SDRAM_WriteRead_8Bit(void)
{
    uint32_t test_end_addr = SDRAM_END_ADDR;
    uint32_t Address = 0x00;
    uint32_t i = 0;

    /** Fill 0xFF */
    Address = 0x60000000;
    for (i = 0; Address < test_end_addr + 0x100; i++, Address++)
    {
        *( uint8_t*) (Address) = 0xFF;
    }

    /** Write value to addressŁ¨unit: wordŁ©*/
    Address = SDRAM_START_ADDR;
    for (i = 0; Address < test_end_addr; i++, Address++)
    {
        *( uint8_t*) (Address) = (uint8_t)(Address >> (8 * (i & 0x00000003)));
    }

    /** Check */
    Address = SDRAM_START_ADDR;
    for (i = 0; Address < test_end_addr; i++, Address++)
    {
        if (*(uint8_t*) (Address) != (uint8_t)(Address >> (8 * (i & 0x00000003))))
        {
            return Address;
        }
    }

    return 0;
}

/*!
 * @brief       SDRAM 16bit Write Read
 *
 * @param       None
 *
 * @retval      None
 */
uint32_t DMC_SDRAM_WriteRead_16Bit(void)
{
    uint32_t Address = 0x60000000;
    uint32_t i = 0;

    /** Fill 0xFF */
    for (i = 0; Address < SDRAM_END_ADDR; i++, Address+=2)
    {
        *( uint16_t*) (Address) = 0xFFFF;
    }

    /** Write value to addressŁ¨unit: wordŁ©*/
    Address = SDRAM_START_ADDR;
    for (i = 0; Address < SDRAM_END_ADDR; i++, Address+=2)
    {
        *( uint16_t*) (Address) = (uint16_t)(Address >> (8 * (i & 0x00000003)));
    }

    /** Check */
    Address = SDRAM_START_ADDR;
    for (i = 0; Address < SDRAM_END_ADDR; i++, Address+=2)
    {
        if (*(uint16_t*) (Address) != (uint16_t)(Address >> (8 * (i & 0x00000003))))
        {
            return Address;
        }
    }

    return 0;
}

/*!
 * @brief       SDRAM 32bit Write Read
 *
 * @param       None
 *
 * @retval      None
 */
uint32_t DMC_SDRAM_WriteRead_32Bit(void)
{
    uint32_t Address = 0x60000000;
    uint32_t i = 0;

    /** Fill 0xFF */
    for (i = 0; Address < SDRAM_END_ADDR; i++, Address+=4)
    {
        *( uint32_t*) (Address) = 0xFFFFFFFF;
    }

    /** Write value to addressŁ¨unit: wordŁ©*/
    Address = SDRAM_START_ADDR;
    for (i = 0; Address < SDRAM_END_ADDR; i++, Address+=4)
    {
        *( uint32_t*) (Address) = (uint32_t)Address;
    }

    /** Check */
    Address = SDRAM_START_ADDR;
    for (i = 0; Address < SDRAM_END_ADDR; i++, Address+=4)
    {
        if (*(uint32_t*) (Address) != (uint32_t)Address)
        {
            return Address;
        }
    }

    return 0;
}

/*!
 * @brief       Delay
 *
 * @param       None
 *
 * @retval      None
 */
void Delay(void)
{
    tick = 0;

    while (tick < 500);
}

/*!
* @brief       Redirect C Library function printf to serial port.
*              After Redirection, you can use printf function.
*
* @param       ch:  The characters that need to be send.
*
* @param       *f:  pointer to a FILE that can recording all information
*              needed to control a stream
*
* @retval      The characters that need to be send.
*
*/
int fputc(int ch, FILE* f)
{
    /** send a byte of data to the serial port */
    USART_TxData(DEBUG_USART, (uint8_t)ch);

    /** wait for the data to be send  */
    while (USART_ReadStatusFlag(DEBUG_USART, USART_FLAG_TXBE) == RESET);

    return (ch);
}
